package iu.gq.template;


import iu.gq.db.DbAdapter;
import iu.gq.db.items.ChapterDetail;
import iu.gq.db.items.ChapterItem;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;
import com.gq.utils.MyViewPager;
import com.gq.utils.NetworkState;
import com.gq.utils.SharePreferenceUtil;
import com.gq.widget.actionbar.ActionBarActivity;

public class ReaderActivity extends ActionBarActivity implements OnTouchListener, OnClickListener {

	public static final int TIMER = 2000;
	
	private MyViewPager viewPager;
	private AdView adView;
	private Handler mHandler;
	private ArrayList<ChapterItem> mChapterListItem;
	private ChapterItem mCurrentChapter;
	private ImageView btnNext, btnPrev;
	private int currentPosition = 0;
	
	private Runnable loadAdsRun = new Runnable() {
		
		@Override
		public void run() {
			if (adView != null) {
				adView.stopLoading();
				adView.loadAd(new AdRequest());
			}
		}
	};
	
	private Runnable hideButtonRun = new Runnable() {
		
		@Override
		public void run() {
			if (btnNext != null) btnNext.setVisibility(View.GONE);
			if (btnPrev != null) btnPrev.setVisibility(View.GONE);
		}
	};
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reader_scr);
		new NetworkState(ReaderActivity.this).check();
		mHandler = new Handler();
		currentPosition = getIntent().getExtras().getInt("POSITION");
		if (currentPosition < 0) currentPosition = 0;
		mChapterListItem = getIntent().getParcelableArrayListExtra("CHAPTER_LIST");
		viewPager = (MyViewPager) findViewById(R.id.viewPager);
		btnNext = (ImageView) findViewById(R.id.btnNext);
		btnNext.setOnClickListener(this);
		btnPrev = (ImageView) findViewById(R.id.btnPrev);
		btnPrev.setOnClickListener(this);
		
		
		adView = (AdView) findViewById(R.id.adView);
		adView.setAdListener(new AdListener() {
			
			@Override
			public void onReceiveAd(Ad ad) {
				mHandler.removeCallbacks(loadAdsRun);
				mHandler.postDelayed(loadAdsRun, 30000);
			}
			
			@Override
			public void onPresentScreen(Ad ad) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLeaveApplication(Ad ad) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onFailedToReceiveAd(Ad ad, ErrorCode e) {
				mHandler.removeCallbacks(loadAdsRun);
				mHandler.postDelayed(loadAdsRun, 10000);
			}
			
			@Override
			public void onDismissScreen(Ad ad) {
				// TODO Auto-generated method stub
				
			}
		});
		final ReaderAdapter adapter = new ReaderAdapter(this);
		showButton(false);
		adapter.load(new Runnable() {
			
			@Override
			public void run() {
				viewPager.setAdapter(adapter);
				if (GQConst.SHOW_NEXT_PREV_BTN) showButton(true);
			}
		});
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				mCurrentChapter = mChapterListItem.get(position);
				mCurrentChapter.setPosition(position);
				currentPosition = position;
				if (adView != null) {
					mHandler.removeCallbacks(loadAdsRun);
					adView.loadAd(new AdRequest());
				}
				mHandler.removeCallbacks(hideButtonRun);
				showButtonTimer(true);
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}
			
			@Override
			public void onPageScrollStateChanged(int position) {
			}
		});
		viewPager.setCurrentItem(currentPosition);
		if (mChapterListItem != null) { 
			mCurrentChapter = mChapterListItem.get(currentPosition);
			mCurrentChapter.setPosition(currentPosition);
		}
//		viewPager.setCurrentItem(getLastPage());
	}
	
	public int countHtmlFilesInAsset() {
		AssetManager assetmgr = getAssets();
		int count = 0;
		try {
			String[] files = assetmgr.list("");
			for (String f : files) {
				if (f.matches("\\d+\\.html")) count++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return count;
	}
	
	public void setLastChapter(ChapterItem chapter) {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		Editor editor = sharePreference.edit();
		editor.putString("lastchapter", chapter.toJson());
		editor.commit();
	}
	
	public ChapterItem getLastChapter() {
		SharedPreferences sharePreference = getPreferences(MODE_PRIVATE);
		String jsonStr = sharePreference.getString("lastchapter", String.valueOf(null));
		ChapterItem item = null;
		try {
			item = new ChapterItem(new JSONObject(jsonStr));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return item;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (GQConst.SHOW_NEXT_PREV_BTN) {
			viewPager.setPagingEnable(false);
			showButtonTimer(true);
		} else {
			viewPager.setPagingEnable(true);
			showButton(false);
		}
		adView.loadAd(new AdRequest());
	}
	
	@Override
	protected void onStop() {
		if (adView != null) {
			adView.stopLoading();
			mHandler.removeCallbacks(loadAdsRun);
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (adView != null) adView.destroy();
		super.onDestroy();
	}
	
	private class ReaderAdapter extends PagerAdapter {

		private Context context;
		private LayoutInflater mInflater;
		
		public ReaderAdapter(Context context) {
			this.context = context;
			mInflater = LayoutInflater.from(context);
		}
		
		public void load(final Runnable run) {
			if (mChapterListItem == null) {
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						mChapterListItem = (ArrayList<ChapterItem>) new DbAdapter(context).getAllChapterItems();
					}
				}).run();
			}
			runOnUiThread(run);
			
		}
		
		
		@Override
		public int getCount() {
			return mChapterListItem.size();
		}
		
		public String getItem(int position) {
			ChapterDetail detail = new DbAdapter(this.context).getChapterDetailById(mChapterListItem.get(position).getId());
			String detailcontent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body style='text-align:justify; font-size:1.2em;'>"+detail.getDetail()+"</body></html>";
			detailcontent = detailcontent.replaceAll("%", "&#37;");
			return detailcontent;
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == (View) object;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			ViewGroup viewGroup = (ViewGroup) mInflater.inflate(R.layout.web_view, null, false);
			final WebView webView = (WebView) viewGroup.findViewById(R.id.web_view);
			webView.setOnTouchListener(ReaderActivity.this);
			final ProgressBar progressBar = (ProgressBar) viewGroup.findViewById(R.id.progress_bar);
			final TextView textView = (TextView) viewGroup.findViewById(R.id.text_view);
			progressBar.setVisibility(View.VISIBLE);
			webView.setVisibility(View.GONE);
			textView.setVisibility(View.VISIBLE);
			if (GQConst.LOAD_IMAGE_WEBVIEW)
				webView.loadDataWithBaseURL("file:///android_asset/", getItem(position), "text/html", "UTF-8", "");
			else
				webView.loadData(getItem(position), "text/html; charset=UTF-8", null);
			webView.setWebViewClient(new WebViewClient() {

				@Override
				public void onPageFinished(WebView view, String url) {
					progressBar.setVisibility(View.GONE);
					textView.setVisibility(View.GONE);
					webView.setVisibility(View.VISIBLE);
					super.onPageFinished(view, url);
				}
				
			});
			webView.setVisibility(View.VISIBLE);
			((ViewPager) container).addView(viewGroup);
			return viewGroup;
			
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.read, menu);
//		getActionBarHelper().setDisplayHomeAsUpEnabled(true);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
//			case android.R.id.home:
//				onBackPressed();
//				break;
			
			case R.id.menu_bookmark:
				SharePreferenceUtil.getInstance(ReaderActivity.this).setLastChapter(mCurrentChapter);
				Toast.makeText(ReaderActivity.this, "Đã lưu chương "+mCurrentChapter.getTitle(), Toast.LENGTH_SHORT).show();
				break;
			
			case R.id.menu_info:
				try {
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GQConst.SEARCHURI)));
				} catch (Exception e) {
					Toast.makeText(ReaderActivity.this, "Máy bạn không cài đặt ứng dụng Google Play", Toast.LENGTH_SHORT).show();
				}
				break;
				
			case R.id.menu_save:
				AlertDialog.Builder builder = new AlertDialog.Builder(ReaderActivity.this);
				builder.setMessage("Bạn muốn lưu lại trang hiện tại?")
				.setCancelable(true)
				.setPositiveButton("Có", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
//						setLastChapter(mCurrentChapter);
						SharePreferenceUtil.getInstance(ReaderActivity.this).setLastChapter(mCurrentChapter);
						Toast.makeText(ReaderActivity.this, "Đã lưu chương "+mCurrentChapter.getTitle(), Toast.LENGTH_SHORT).show();
						dialog.cancel();
					}
				})
				.setNegativeButton("Không", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	@Override
	public boolean onTouch(View v, MotionEvent evt) {
		final int action = evt.getAction();
		switch(action & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				showButtonTimer(true);
				break;
			case MotionEvent.ACTION_UP:
				showButtonTimer(false);
				break;
		}
		return false;
	}

	public static void startReaderActivity(Context context, ArrayList<? extends Parcelable> chapterList, int position) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putParcelableArrayListExtra("CHAPTER_LIST", (ArrayList<? extends Parcelable>) chapterList);
		intent.putExtra("POSITION", position);
		context.startActivity(intent);
	}
	
	public void showButtonTimer(boolean isShow) {
		mHandler.removeCallbacks(hideButtonRun);
		if (isShow) {
			btnNext.setVisibility(View.VISIBLE);
			btnPrev.setVisibility(View.VISIBLE);
			mHandler.postDelayed(hideButtonRun, TIMER);
		} else {
			mHandler.postDelayed(hideButtonRun, TIMER);
		}
	}
	
	public void showButton(boolean isShow) {
		if (isShow) {
			btnNext.setVisibility(View.VISIBLE);
			btnPrev.setVisibility(View.VISIBLE);
		} else {
			btnNext.setVisibility(View.GONE);
			btnPrev.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v.equals(btnNext)) {
			if (currentPosition == mChapterListItem.size() - 1)  Toast.makeText(ReaderActivity.this, "Hết! Chúc các bạn vui vẻ", Toast.LENGTH_SHORT).show();
			if (currentPosition <= mChapterListItem.size() - 1) {
				viewPager.setCurrentItem(currentPosition + 1);
			}
		} else if (v.equals(btnPrev)) {
			if (currentPosition > 0) {
				viewPager.setCurrentItem(currentPosition - 1);
			}
		}
	}
}
